//
//  WKSubmitQuestionCell.m
//  WKMaybell
//
//  Created by 何文虎 on 2018/12/26.
//  Copyright © 2018 何文虎. All rights reserved.
//

#import "WKSubmitQuestionCell.h"
#import "WKSwitch.h"


@interface WKQuestionPhotoCell : UICollectionViewCell
@property(nonatomic,strong)UIImageView *imgView;
@property(nonatomic,strong)UIImage *img;

@end

@implementation WKQuestionPhotoCell

- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        self.imgView = [[UIImageView alloc]initWithFrame:self.contentView.bounds];
        [self.contentView addSubview:self.imgView];
        self.layer.cornerRadius = 5;
        self.layer.masksToBounds = YES;
        self.imgView.layer.cornerRadius = 5;
        self.imgView.layer.masksToBounds = YES;
        self.imgView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return self;
}

-(void)setImg:(UIImage *)img{
    _img = img;
    self.imgView.image = img;
}

@end

@interface WKSubmitQuestionCell ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *imgArr;
@property (nonatomic, strong) NSMutableArray<PHAsset *> *selectAssets;
@property(nonatomic,strong)WKSwitch *myswitch;
@end

@implementation WKSubmitQuestionCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        if ([reuseIdentifier isEqualToString:@"QUESTIONTITLE"]) {
            [self setupTitleView];
        }
        
        if ([reuseIdentifier isEqualToString:@"QUESTIONTAG"]) {
            [self setupTagView];
        }
        
        if ([reuseIdentifier isEqualToString:@"QUESTIONTEXT"]) {
            [self setupTextView];
        }
        
        if ([reuseIdentifier isEqualToString:@"QUESTIONSAN"]) {
            [self setupSanView];
        }
        
        if ([reuseIdentifier isEqualToString:@"QUESTIONPHOTO"]) {
            [self setupAddphotoView];
        }
        
        if ([reuseIdentifier isEqualToString:@"QUESTIONYAO"]) {
            [self setupYaoqingView];
        }
        
       
       
    }
    return self;
}

#pragma mark - 添加标题
- (void)setupTitleView{
    
    self.backgroundColor = [UIColor whiteColor];
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(12, 10, ScreenWidth-12-12-40, 26)];
    textField.placeholder = @"有趣的标题更容易让大家看到";
    [self.contentView addSubview:textField];
    UILabel *countLb = [[UILabel alloc]init];
    [self.contentView addSubview:countLb];
    countLb.frame = CGRectMake(ScreenWidth-12-40, 10, 40, 26);
    countLb.text = @"0/20";
    [[textField rac_textSignal]subscribeNext:^(NSString * _Nullable x) {
        
        if (x.length>20) {
            textField.text = [x substringWithRange:NSMakeRange(0, 20)];
        }
        countLb.text = [NSString stringWithFormat:@"%ld/20",x.length];
        
    }];
}

#pragma mark - 添加标签
- (void)setupTagView{
    
    self.backgroundColor = [UIColor whiteColor];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(12, 8, 70, 30)];
    lable.textColor = UIColorFromHex(0x3C3C3C);
    lable.font = PFSC_MediumFont(15);
    NSString *tagStr = @"*添加标签";
    [WHAttributedString setRichTextOnlyColor:lable titleString:tagStr textColor:UIColorFromHex(0xF54050) colorRang:NSMakeRange(0, 1)];
    [self.contentView addSubview:lable];
    
    UILabel *waingLb = [[UILabel alloc]initWithFrame:CGRectMake(90, 8, ScreenWidth-90-12-17-5, 30)];
    waingLb.backgroundColor = [UIColor yellowColor];
    waingLb.textColor = UIColorFromHex(0x979797);
    waingLb.font = PFSC_MediumFont(12);
    [self.contentView addSubview:waingLb];
    
    UIButton* addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addButton addTarget:self action:@selector(addtagAction) forControlEvents:UIControlEventTouchUpInside];
    addButton.frame = CGRectMake(ScreenWidth-17-12, 13,17, 17);
    addButton.backgroundColor = [UIColor greenColor];
    addButton.layer.cornerRadius = 17/2;
    addButton.layer.masksToBounds = YES;
    [self.contentView addSubview:addButton];
}


- (void)addtagAction{
    NSLog(@"添加标签");
}


#pragma mark - 输入内容
- (void)setupTextView{
    
    self.backgroundColor = [UIColor whiteColor];
    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(12, 0, ScreenWidth-24, 150)];
    textView.placeholder = @"想美~就要大胆问出来";
    textView.textColor = UIColorFromHex(0x3C3C3C);
    textView.font = PFSC_MediumFont(15);
    [self.contentView addSubview:textView];
    
    UILabel *waingLb = [[UILabel alloc]init];
    waingLb.backgroundColor = [UIColor yellowColor];
    waingLb.textColor = UIColorFromHex(0x979797);
    waingLb.font = PFSC_MediumFont(12);
    waingLb.text = @"0/140";
    waingLb.textAlignment = NSTextAlignmentRight;
    [self.contentView addSubview:waingLb];
    [waingLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-12);
        make.bottom.mas_offset(-15);
        make.width.mas_offset(60);
    }];
    
    
    [[textView rac_textSignal]subscribeNext:^(NSString * _Nullable x) {
        NSInteger yslength = x.length;
        NSInteger sylength = 140 - yslength;
        waingLb.text = [NSString stringWithFormat:@"%ld/%ld",yslength,sylength];
    }];
}



#pragma mark - 悬赏
- (void)setupSanView{
    
    self.backgroundColor = UIColorFromHex(0xF8F8F8);
    UIView *bgView = [[UIView alloc]init];
    [self.contentView addSubview:bgView];
    bgView.backgroundColor = [UIColor whiteColor];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.with.mas_equalTo(0);
        make.height.mas_equalTo(46);
        make.centerY.mas_equalTo(self.mas_centerY);
    }];
    
    UIButton *sanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sanBtn.frame = CGRectMake(12, 8, 100, 30);
    [bgView addSubview:sanBtn];
    [sanBtn addTarget:self action:@selector(sanAction:) forControlEvents:UIControlEventTouchUpInside];
    [sanBtn setTitle:@"问答悬赏" forState:UIControlStateNormal];
    [sanBtn setTitleColor:UIColorFromHex(0x3C3C3C3) forState:UIControlStateNormal];
    sanBtn.titleLabel.font = PFSC_MediumFont(15);
    
}

- (void)sanAction:(UIButton*)sender{
    
}

#pragma mark 邀请好友
- (void)setupYaoqingView{
    
    self.backgroundColor = [UIColor whiteColor];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(12, 8, 200, 30)];
    lable.textColor = UIColorFromHex(0x3C3C3C);
    lable.font = PFSC_MediumFont(15);
    lable.text = @"邀请美圈好友回答此问题";
    [self.contentView addSubview:lable];
    
    //语音提示开关
    self.myswitch = [[WKSwitch alloc] initWithFrame:CGRectMake(ScreenWidth-60-12, 10, 60, 25)];
    [_myswitch setTransform:CGAffineTransformMakeScale(0.9, 0.9)];
    _myswitch.on = YES;
    _myswitch.thumbTintColor = [UIColor whiteColor];
    _myswitch.onTintColor = UIColorFromHex(0xF54050);
    _myswitch.tintColor =  UIColorFromHex(0x999999);
    [_myswitch addTarget:self action:@selector(switchPressed:) forControlEvents:UIControlEventValueChanged];
    [self.contentView addSubview:_myswitch];
}

- (void)switchPressed:(UISwitch *)switchs{
    if (switchs.on == YES) {
        
    }else{
        
    }
}



#pragma mark 添加图片
- (void)displayImgWithImgArr:(NSArray*)imgs{
    
    self.imgArr = imgs.mutableCopy;
    
    [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
    [self setupAddphotoView];
}


- (void)setupAddphotoView{
    
    self.backgroundColor = [UIColor whiteColor];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(12, 8, 70, 30)];
    lable.textColor = UIColorFromHex(0x3C3C3C);
    lable.font = PFSC_MediumFont(15);
    lable.text = @"添加图片";
    [self.contentView addSubview:lable];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(12, 45, ScreenWidth-24, 1)];
    lineView.backgroundColor = UIColorFromHex(0Xf8f8f8);
    [self.contentView addSubview:lineView];
    
    [self addSelectPhotoView];
    
}

- (void)addSelectPhotoView{
    
    CGFloat height = 0;
    CGFloat itemHeigth = (ScreenWidth - 24 -10)/3;
    height = itemHeigth*3+10+5*2;
    
    if (self.imgArr.count>=3 && self.imgArr.count<6) {
        
        height = itemHeigth*2+10+5;
    }else if(self.imgArr.count>=6){
        height =  itemHeigth*3+10+5*2;
    }else{
        height = itemHeigth + 10;
    }
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(itemHeigth-1, itemHeigth-1);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12);
    layout.sectionHeadersPinToVisibleBounds = NO;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,46+15,ScreenWidth,height) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.collectionView];
    
    [self.collectionView registerClass:[WKQuestionPhotoCell class] forCellWithReuseIdentifier:NSStringFromClass([WKQuestionPhotoCell class])];
    
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    
    _collectionView.layer.masksToBounds = YES;
    
    [self setUpLongPressGes];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger count =  self.imgArr.count<9 ?  self.imgArr.count+1 : self.imgArr.count;
    return count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WKQuestionPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WKQuestionPhotoCell class]) forIndexPath:indexPath];
    cell.backgroundColor = [UIColor magentaColor];
    if(indexPath.row<self.imgArr.count){
        cell.img = self.imgArr[indexPath.row];
    }
    
    return cell;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZLPhotoActionSheet *ac = [[ZLPhotoActionSheet alloc] init];
    ac.configuration.maxSelectCount = 9;
    ac.configuration.maxPreviewCount = 10;
    ac.sender = [WHUtiities currentViewController];
    
    ac.configuration.allowSelectVideo = NO;
    ac.configuration.allowSelectImage = YES;
    
    //    ac.configuration.allowEditVideo = NO;
    //    ac.configuration.maxVideoDuration = 10;
    
    if (indexPath.row==self.imgArr.count || self.imgArr.count<=0) {
        //选择回调
        @weakify(self);
        [ac setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
            @strongify(self);
            [self.imgArr addObjectsFromArray:images];
            [self.selectAssets addObjectsFromArray:assets];
            
            if (self.selectImgBlock) {
                self.selectImgBlock(self.imgArr);
            }
            
            [collectionView reloadData];
            
        }];
        
        //调用相册
        [ac showPreviewAnimated:YES];
        
        //    //预览网络图片
        //    [ac previewPhotos:arrNetImages index:0 hideToolBar:YES complete:^(NSArray * _Nonnull photos) {
        //        //your codes
        //    }];
        
        
        
    }else{
        
        [ac previewSelectedPhotos:self.imgArr assets:self.selectAssets index:indexPath.row isOriginal:YES];
        
    }
}




#pragma mark - 添加长按手势
- (void)setUpLongPressGes {
    UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    [self.collectionView addGestureRecognizer:longPresssGes];
}

- (void)longPressMethod:(UILongPressGestureRecognizer *)longPressGes {
    
    // 判断手势状态
    switch (longPressGes.state) {
            
        case UIGestureRecognizerStateBegan: {
            
            // 判断手势落点位置是否在路径上(长按cell时,显示对应cell的位置,如path = 1 - 0,即表示长按的是第1组第0个cell). 点击除了cell的其他地方皆显示为null
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPressGes locationInView:self.collectionView]];
            // 如果点击的位置不是cell,break
            if (nil == indexPath) {
                break;
            }
            NSLog(@"%@",indexPath);
            // 在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
            
        case UIGestureRecognizerStateChanged:
            // 移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longPressGes locationInView:self.collectionView]];
            break;
            
        case UIGestureRecognizerStateEnded:
            // 移动结束后关闭cell移动
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

// 在开始移动时会调用此代理方法，
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==self.imgArr.count || self.imgArr.count<=0) {
        return NO;
    }
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    
    //取出源item数据
    id objc = [self.imgArr objectAtIndex:sourceIndexPath.item];
    //从资源数组中移除该数据
    [self.imgArr removeObject:objc];
    //将数据插入到资源数组中的目标位置上
    [self.imgArr insertObject:objc atIndex:destinationIndexPath.item];
    
    
    
    
    
}



- (NSMutableArray*)imgArr{
    if (!_imgArr) {
        _imgArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _imgArr;
}

- (NSMutableArray*)selectAssets{
    if (!_selectAssets) {
        _selectAssets = [NSMutableArray array];
    }
    return _selectAssets;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
